package logic

import (
	"context"
	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	// "fmt"
	"strconv"

	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)


type ServeyCreateLogic struct{
	logx.Logger
	ctx context.Context
	svcCtx *svc.ServiceContext
	modelS model.ServeyModel
	modelSSC model.SevSevClfModel
	modelSC model.ServeyClassifyModel
}

func NewServeyCreateLogic(ctx context.Context,svcCtx *svc.ServiceContext)*ServeyCreateLogic{
	return &ServeyCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx: ctx,
		svcCtx: svcCtx,
		modelS: model.NewServeyModel(svcCtx.Orm,svcCtx.Config.Cache),
		modelSSC: model.NewSevSevClfModel(svcCtx.Orm),
		modelSC: model.NewServeyClassifyModel(svcCtx.Orm,svcCtx.GormDB),
	}
}

func (l *ServeyCreateLogic)Create(req *types.ServeyCreateRequest)(resp *types.StandredIdResponse,err error){
	payload,ok := l.ctx.Value("payload").(string)
	if !ok{
		return nil,errorx.NewBizError(500,"用户ID获取失败")
	}
	userId,err := strconv.ParseInt(payload,10,64)
	if err != nil{
		return nil,errorx.NewBizError(500,"字符串格式转换错误")
	}
	var sId int64
	err = l.modelS.Trans(l.ctx,func(context context.Context, session sqlx.Session) error {

		sev := &model.Servey{
			CreatorId: userId,
			CreateTime: time.Now().Unix(),
			EndTime: time.Now().Unix(),
			PublishTime: time.Now().Unix(),
			IsPublic: 1,
			IsEnd: 1,
			IsDeleted: 1,
			Title: req.Title,
			Description: req.Description,
			VisitNum: 0,
		}
		// // step1 存储问卷
		sId,err = l.modelS.InsertGetId(context,session,sev)
		if err != nil {
			return errorx.NewBizError(500,"插入数据错误，请重试")
		}
	    // // step2 存储问卷分类和问卷的关系对应 
		if len(req.Ids) > 0 {
			err = l.modelSSC.BulkInsert(context,session,req.Ids,sId)
			if err != nil {
				return errorx.NewBizError(500,"插入数据错误，请重试")
			}
		}
		// step3 更新问卷分类下标下的数量
		if len(req.Ids) > 0 {
			err = l.modelSC.RowsUpdateNum(l.ctx,session,0,1,req.Ids)
		}
		return err
	})
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}
	return &types.StandredIdResponse{
		Code: 200,
		Msg: "插入成功",
		Data: types.IdRequest{
			Id: sId,
		},
	},nil
}